package com.zs.grain

import android.app.AlarmManager
import android.app.PendingIntent
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import com.xnkj1688.semplibrary.mvvm.ViewManager
import com.zs.grain.ui.MainActivity

/**
 * Created by Wesley on 2017/8/19.
 */

class ExceptionHandler(private val myApp: MyApplication) : Thread.UncaughtExceptionHandler {

    override fun uncaughtException(t: Thread, e: Throwable) {
        e.printStackTrace()
        try {
            ViewManager.instance.finishAllActivity()

            var homeIntent = Intent(Intent.ACTION_MAIN, null)
            homeIntent.addCategory(Intent.CATEGORY_HOME)
            val list = myApp.packageManager.queryIntentActivities(homeIntent, 0)
            for (info in list) {
                if (info.activityInfo.packageName == myApp.applicationInfo.packageName) {
                    val pkg = info.activityInfo.packageName
                    val cls = info.activityInfo.name
                    val componet = ComponentName(pkg, cls)
                    homeIntent = Intent()
                    homeIntent.component = componet
                    homeIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                    myApp.startActivity(homeIntent)
                    break
                }
            }
        } catch (ex: Exception) {
            ex.printStackTrace()
        }

        var alarmManager = myApp.getSystemService(Context.ALARM_SERVICE) as AlarmManager
        var contentIntent = PendingIntent.getActivity(myApp, 0, Intent(myApp, MainActivity::class.java), 0);
        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 5000, contentIntent);
        ViewManager.instance.exitApp(myApp)
        System.exit(0)
    }
}
